package com.proxy.scanandcheck.checker.dao;

import java.io.File;
import java.io.FileNotFoundException;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;

import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanHandler;

import com.proxy.scanandcheck.common.util.Constants;
import com.proxy.scanandcheck.common.util.DataSourceUtil;
import com.proxy.scanandcheck.common.valueobject.Proxy;

public class ProxyDao {
	
	public List<Proxy> getProxyList() throws FileNotFoundException
	{
		File file = new File(Constants.PROXIES_TXT_PATH);
		Scanner scanner = new Scanner(file);
		List<Proxy> proxyList = new ArrayList<Proxy>();
		while(scanner.hasNext())
		{
			Proxy proxy = new Proxy();
			proxy.setProxy(scanner.next());
			proxyList.add(proxy);
		}
		return proxyList;
	}
	
	/**
	 * Create proxy record or update record if record exits to specific table
	 * @param myProxy
	 * @throws SQLException
	 */
	@SuppressWarnings("unchecked")
	public void createOrUpdateProxies(Proxy myProxy) throws SQLException
	{
        try {
            QueryRunner qr = new QueryRunner(DataSourceUtil.getDataSource());
            Proxy tempProxy = (Proxy) qr.query( 
            		"SELECT * FROM proxies where proxy = ?", 
            			new BeanHandler(Proxy.class), 
            				myProxy.getProxy()); 
            if (tempProxy == null)
            {
            	String sql = "INSERT INTO proxies (proxy, ip_class, last_update) VALUES (?,?,?)"; 
            	qr.update( sql, myProxy.getProxy(),myProxy.getIpClass(), myProxy.getUpdateTimeForGoogleHost()); 
            }
            else
            {
            	String sql = "UPDATE proxies SET last_update=? WHERE proxy = ?"; 
            	qr.update( sql, myProxy.getUpdateTimeForGoogleHost(), myProxy.getProxy()); 
            }
            
            
        } catch (SQLException e) {
            e.printStackTrace();
            throw e;
        } 
	}

}
